package org.stjs.generator.check.expression;

import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;

import org.stjs.generator.GenerationContext;
import org.stjs.generator.check.CheckContributor;
import org.stjs.generator.check.CheckVisitor;
import org.stjs.generator.javac.InternalUtils;
import org.stjs.generator.javac.TreeWrapper;
import org.stjs.generator.utils.JavaNodes;

import com.sun.source.tree.ClassTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;

public class NewClassInlineFunctionCheck implements CheckContributor<NewClassTree> {

	private boolean checkMember(Tree member, GenerationContext<Void> context, boolean hasMethod) {
		Element memberElement = JavaNodes.elementFromDeclaration(member);
		if (memberElement.getKind() == ElementKind.METHOD && !hasMethod) {
			return true;
		}
		if (InternalUtils.isSynthetic(member)) {
			// constructors generated by the compiler are ignored
			return false;
		}
		context.addError(member, "Initialization block for a Javascript function must contain exactly one method");
		return false;
	}

	@Override
	public Void visit(CheckVisitor visitor, NewClassTree tree, GenerationContext<Void> context) {
		TreeWrapper<ClassTree, Void> tw = context.getCurrentWrapper();
		if (!tw.child(tree.getIdentifier()).isJavaScriptFunction()) {
			return null;
		}
		boolean hasMethod = false;
		for (Tree member : tree.getClassBody().getMembers()) {
			hasMethod = checkMember(member, context, hasMethod);
		}
		return null;
	}
}
